import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/utils/log.dart';

class StudentServiceProvider extends GetConnect {
  StudentServiceProvider() {
    httpClient.addResponseModifier((request, response) {
      if (response.statusCode == 403) {
        Log.debug('${request.url} 403 error');
        if (!Get.isSnackbarOpen) {
          Get.snackbar(
            'Message'.tr,
            'You have been logged out due to inactivity or security reasons.'
                .tr,
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Color(0xff23c6c8),
            colorText: Color(0xffd8ffff),
          );
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else if (response.statusCode == 401) {
        Log.debug('${request.url} unauthorized access');
        if (!Get.isSnackbarOpen) {
          Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
              backgroundColor: Color(0xff23c6c8),
              colorText: Color(0xffd8ffff),
              snackPosition: SnackPosition.BOTTOM);
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else {
        Log.debug(response.request?.url.toString());
        return response;
      }
    });
    httpClient.maxAuthRetries = 2;
    httpClient.timeout = Duration(seconds: 30);
  }

  Future<http.Response> getStudentProfile() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse('${Constants.BaseAPI}usermanager/profile');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getClasses() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse('${Constants.BaseAPI}usermanager/getClasses');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<bool> hasNewClassAnnoucement() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPI}schoolmanager/newclassannouncement');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    if (response.statusCode == 200) {
      //Log.debug('RETURNING: ' + response.body);
      if (response.body == 'true')
        return true;
      else
        return false;
    } else {
      return false;
    }
  }

  Future<http.Response> getClassAnnoucement() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPI}schoolmanager/myclassannouncement');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getMyAssignments(String? classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPI}schoolmanager/myassignments/$classId');
    Log.debug(url);
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getLiveAssignments(String? classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPI}schoolmanager/liveassignments/$classId');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getLiveAssignmentDetails(
      String? classId, String? assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse(
        '${Constants.BaseAPI}schoolmanager/liveassignments/$classId/$assignmentId');
    Log.debug(url);
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getAssessments() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse(
        '${Constants.BaseAPISuper}superadmin/assessment/mine/?limit=0&page=0');
    final response = await http.put(url,
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
        body: jsonEncode({}));
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getAssessmentCount() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPISuper}superadmin/assessment/mine/count');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getPlacementTestCount() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse(
        '${Constants.BaseAPISuper}superadmin/question/record/count?PRE_TEST');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getReportBaskets(String? limit, String? page) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (limit == null) limit = '0';
    if (page == null) page = '0';
    Uri url = Uri.parse(
        '${Constants.BaseAPI}superadmin/basket/player?limit=$limit&page=$page&sortField=-when');
    final response = await http.post(url,
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
        body: jsonEncode({'content': [], 'status': []}));
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<dynamic> getChildrenHistory(String userName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}usermanager/children/history/$userName',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<http.Response> getReadingRecords() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse('${Constants.BaseAPI}superadmin/history');
    final response = await http.get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  //used for report
  Future<http.Response> getAssignmentRecordsByClass(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url =
        Uri.parse('${Constants.BaseAPI}schoolmanager/myassignments/$classId');
    final response = await http.get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

  Future<http.Response> getWordStrokesJson(String word) async {
    Uri url = Uri.parse(
        'https://cdn.jsdelivr.net/npm/hanzi-writer-data@2.0/$word.json');
    final response = await http.get(
      url,
    );
    return response;
  }
}
